<template>
  <el-dialog v-model="dialogVisible" :title="title == 'add' ? '新增' : '编辑'" width="30%" :before-close="handleClose">
    <div class="custom-manage-dialog">
      <el-tabs v-model="activeName" type="card" class="demo-tabs">
        <el-tab-pane label="基本信息" name="first">
          <tab1 ref="tab1Ref" :formList="topTable" />
        </el-tab-pane>
        <el-tab-pane label="联系人信息" name="second" v-if="title == 'add'">
          <tab2 ref="tab2Ref" :formList="contacts" />
        </el-tab-pane>
        <el-tab-pane label="更多信息" name="third">
          <tab3 ref="tab3Ref" :topTable="topTable" :bottomTable="bottomTable" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submit"> 提交 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { customerApi, contactsApi, getAddressOptions } from "@/plugins/api/customer/setup/fifth";
import { listApi as dictApi } from "@/plugins/api/system/dict";
import { addApi, saveApi } from "@/plugins/api/customer/manage/pool";
import tab1 from "./DialogPool-tab1.vue";
import tab2 from "./DialogPool-tab2.vue";
import tab3 from "./DialogPool-tab3.vue";
import { events } from "@/plugins/eventBus";
//
let tab1Ref = ref(null);
let tab2Ref = ref(null);
let tab3Ref = ref(null);
let dialogVisible = ref(false);
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => { });
}
let title = ref("");

let activeName = ref("third");
let ruleForm = ref({});
function initFun(type, row) {
  activeName.value = "first";
  submitArr.value = [];
  title.value = type;
  dialogVisible.value = true;
  if (type == "update") {
    ruleForm.value = Object.assign({}, row);
    nextTick(() => {
      tab1Ref.value.updateFun(row);
      tab3Ref.value.updateFun(row);
    });
  } else {
    nextTick(() => {
      tab1Ref.value.initFun();
      tab2Ref.value.initFun();
      tab3Ref.value.initFun();
    });
  }
  //
}

const emit = defineEmits(["refreshTable"]);
// 获取客户数据
let topTable = ref([]);
let bottomTable = ref([]);
function getCustomer(type) {
  return new Promise((resolve, reject) => {
    customerApi({
      is_base: type,
    }).then((data) => {
      if (type == 1) {
        topTable.value = data;
        getTerm(topTable.value);
      } else {
        bottomTable.value = data;
        getTerm(bottomTable.value);
      }
      resolve(data);
    });
  });
}
// 获取联系人数据
let contacts = ref([]);

function getContacts(type) {
  return new Promise((resolve, reject) => {
    contactsApi({
      is_sys: type,
    }).then((data) => {
      contacts.value = contacts.value.concat(data);
      resolve(data);
    });
  });
}
//
function getTerm(arr) {
  if (!Array.isArray(arr)) return;
  arr.forEach((item) => {
    if (
      item.form_type == "select" ||
      item.form_type == "radio" ||
      item.form_type == "checkbox"
    ) {
      getDictionary(item.field_id, item.dict_id, arr);
    } else if (item.form_type == "region") {
      getRegion(item.field_id, item.dict_id, arr);
    }
  });
}
// 获取字典项
function getDictionary(id, dict_id, list) {
  return new Promise((resolve, reject) => {
    dictApi({ dict_id: dict_id }).then((data) => {
      if (list) {
        list.forEach((item) => {
          if (item.field_id == id) {
            item.termList = data.map((ele) => {
              return {
                name: ele.name,
                value: ele.name,
              };
            });
          }
        });
      }
      resolve(data);
    });
  });
}
// 获取省市区选择项树
function getRegion(id, dict_id, list) {
  return new Promise((resolve, reject) => {
    getAddressOptions({}).then((data) => {
      if (list) {
        list.forEach((item) => {
          if (item.field_id == id) {
            item.termList = data;
          }
        });
      }
      resolve(data);
    });
  });
}
function submit() {
  events.emit("submitForm");
  events.on("formValidFun", () => {
    //
    submitArr.value = [];
  });

  if (title.value == "add") {
    setTimeout(() => {
      if (submitArr.value.length == 3) {
        if (
          submitArr.value.some((ele) => {
            return ele.identifying == "tab1";
          }) &&
          submitArr.value.some((ele) => {
            return ele.identifying == "tab2";
          }) &&
          submitArr.value.some((ele) => {
            return ele.identifying == "tab3";
          })
        ) {
          let customer = {}; //客户
          let contacts = {}; //联系人
          submitArr.value.forEach((item) => {
            if (item.identifying !== "tab2") {
              for (let i in item) {
                if (i !== "identifying") {
                  customer[i] = item[i];
                }
              }
            } else {
              let obj = Object.assign({}, item);
              delete obj.identifying;
              contacts = Object.assign({}, obj);
            }
          });
          addApi({
            customer: customer,
            contacts: contacts,
          }).then(() => {
            ElMessage.success("添加成功！");
            dialogVisible.value = false;
            activeName.value = "first";
            submitArr.value = [];
            emit("refreshTable");
          });
        }
      }
    });
  } else {
    setTimeout(() => {
      if (submitArr.value.length == 2) {
        if (
          submitArr.value.some((ele) => {
            return ele.identifying == "tab1";
          }) &&
          submitArr.value.some((ele) => {
            return ele.identifying == "tab3";
          })
        ) {
          let customer = {}; //客户
          let contacts = {}; //联系人
          submitArr.value.forEach((item) => {
            if (item.identifying !== "tab2") {
              for (let i in item) {
                if (i !== "identifying") {
                  customer[i] = item[i];
                }
              }
            } else {
              let obj = Object.assign({}, item);
              delete obj.identifying;
              contacts = Object.assign({}, obj);
            }
          });
          customer.id = ruleForm.value.id;
          saveApi(customer).then(() => {
            ElMessage.success("修改成功！");
            dialogVisible.value = false;
            activeName.value = "first";
            submitArr.value = [];
            emit("refreshTable");
          });
        }
      }
    });
  }
}
let submitArr = []; //表单存储
function submitData(data) {
  if (!submitArr.value) submitArr.value = [];
  if (
    !submitArr.value.some((item) => {
      return item.identifying == data.identifying;
    })
  ) {
    submitArr.value.push(data);
  } else {
    submitArr.value.forEach((ele, i) => {
      if (ele.identifying == data.identifying) {
        submitArr.value.splice(i, 1, data);
      }
    });
  }
}
//
onMounted(() => {
  getCustomer(1);
  getCustomer(0);
  getContacts(1).then(() => {
    getContacts(0).then(() => {
      getTerm(contacts.value);
    });
  });
  events.on("formSubmission", (message, identifying) => {
    submitData(message);
  });
});
onBeforeUnmount(() => {
  events.off("formSubmission");
  events.off("formValidFun");
});
defineExpose({
  initFun,
});
</script>
<style scoped lang="scss">
.custom-manage-dialog {
  :deep(.el-form-item) {
    width: 100%;
    margin-right: 0;
    padding-right: 10px;
    box-sizing: border-box;

    .el-input {
      width: 100%;
    }
  }
}
</style>
